package com.study.chapter05.operator.source;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;

import java.util.Random;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2022/7/27 22:31
 */
public class ParallelSourceCustomTest {

    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //使用自定义的SourceFunction，注意对于自定义的直接继承SourceFunction的，并行度只能设置为1，否则会抛出异常
        DataStreamSource<Integer> stream = env.addSource(new ParallelSourceCustom()).setParallelism(2);

        stream.print();

        env.execute();


    }

    //自定义并行sourceFunction
    public static class ParallelSourceCustom implements ParallelSourceFunction<Integer>{
        // 声明一个布尔变量，作为控制数据生成的标识位
        private Boolean running = true;
        private Random random = new Random();

        @Override
        public void run(SourceContext<Integer> ctx) throws Exception {
            while (running){
                ctx.collect(random.nextInt());
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }
}
